package com.ly.mpayment.rest.up.zhaoguo;

import cn.jpush.api.utils.Nullable;
import com.ailk.upp.utils.Base64Utils;
import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import java.io.*;
import java.net.*;
import java.security.Key;
import java.util.*;

@Component
@Path("zhaoguo")
public class ZhaoGuoRest {

	Logger logger = Logger.getLogger(ZhaoGuoRest.class);


	@Autowired
	IUporderService upOrderService;

	@Autowired
	IDownRechargeFlowService flowService;

	@Autowired
	IDownShopInfoService shopService;

	@Autowired
	IUpShopInfoService upShopInfoService;

	/**
	 * @return
	 */
	@Path("callBack")
	@POST
	public synchronized String callBack(@RequestBody String body){
		//:{"Phone":"17797843834","GoodsSN":"1101314","OrderSN":"2c922ab983ac0a600183b2134494695f","State":200,"Remark":null}
		logger.info("zhaoguo_callback:"+ body);
		if(!StringUtils.isBlank(body)){
			JSONObject json = JSONObject.parseObject(body);
			UpOrder order = upOrderService.findById(json.getString("OrderSN"));
			if (order != null && json.getString("State").equals("200") && order.getStatus() == Config.status[0]) {
				order.setRemark(StringUtils.isBlank(json.getString("Remark")) ? "" : URLDecoder.decode(json.getString("Remark")));
				RechargeRest.successUpOrder.add(order);
				UpShopInfo upShopInfo = this.upShopInfoService.findByUserId(order.getUserOrder().getUseruuid());
				return "1";
			}else if(order != null && order.getStatus() == Config.status[0] &&
					(json.getString("State").equals("300") || json.getString("State").equals("400"))){
				order.setRemark(StringUtils.isBlank(json.getString("Remark")) ? "" : URLDecoder.decode(json.getString("Remark")));
				RechargeRest.failtUpOrder.add(order);
				return "1";
			}else{
				logger.info("zhaoguo_not_found_order:" + body +","+ (order == null ? " order is null" : order.getUpphonenum() ));
			}
		}
		return "1";
	}

	/**
	 * @return
	 */
	public void commitOrder(UpOrder order, UpShopInfo shop) {
		UpOrder product = this.upOrderService.findOrderProduct(order.getUporderuuid());
		if (product != null) {
			Map<String,String> headers = new HashMap<>();
			headers.put("appid",shop.getAppId());
			JSONObject data = new JSONObject();
			data.put("Phone",order.getUpphonenum());
			data.put("GoodsSN",order.getUpShopPro().getProductCode());
			Date date = DateUtils.getNowDate();
			data.put("OrderTime",new DateUtils().toTimeStamp());
			data.put("OrderSN",order.getUporderuuid());
			data.put("Type","2");
			data.put("Sign",MD5.md5(StringSort.doSign(data)+"&key="+shop.getUpkey()));
			data.put("OrderTime",DateUtils.toLongDate(date));
			try {
				String des = Base64Utils.encode(desEncrypt(data.toString().getBytes(),shop.getUpshopip().substring(4,12),"UTF-8")) ;
				String res = HttpClient.post10086Url(shop.getOrderCommitAddress(),"="+des,headers);
				//{"code":-1,"msg":"用户无效","data":null}
				logger.info("commitzhaoguo_result:" + data +",phone:"+order.getUpphonenum()+",res:"+res);
				if (!StringUtils.isBlank(res)) {
					JSONObject result = JSONObject.parseObject(res);
					if(result.containsKey("code") && result.getString("code").equals("0")){
						upOrderService.updateUpOrderMsg(order, result.getJSONObject("data").getString("OrderSN"),result.getString("msg"));
					}else if (result.containsKey("code") && !codesError.contains(result.getString("code"))) {
						order.setRemark(result.containsKey("msg") ?	result.getString("msg") : Config.orderFailA);
						RechargeRest.failtUpOrder.add(order);
					}
				} else {
					upOrderService.commitFailt(order,  Config.commitFailt);
					logger.info("commitzhaoguo_error" + order.getUpphonenum());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public static byte[] desEncrypt(byte[] data, String key, String charset) {

		try {
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			byte[] k = charset == null || charset.trim().isEmpty() ? key.getBytes() : key.getBytes(charset);
			SecretKey secretKey = SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(k));
			cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(k));
			return cipher.doFinal(data);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * DES解密
	 * @param data 解密数据
	 * @param key 密钥
	 * @return 返回解密后的数据
	 */

	public static String desDecrypt(byte[] data, String key, String charset) {
		try {
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			byte[] k = charset == null || charset.trim().isEmpty() ? key.getBytes() : key.getBytes(charset);
			cipher.init(Cipher.DECRYPT_MODE, SecretKeyFactory.getInstance("DES").generateSecret(new DESKeySpec(k)), new IvParameterSpec(k));
			if (charset == null || charset.trim().isEmpty()) {
				return new String(cipher.doFinal(data));
			}
			return new String(cipher.doFinal(data), charset);
		} catch (Exception e) {
			return null;
		}

	}

	/**
	 * Http post请求
	 * @param httpUrl 连接
	 * @param param 参数
	 * @return
	 */
	public static String doPost(String httpUrl, @Nullable String param,String appid) {
		StringBuffer result = new StringBuffer();
		//连接
		HttpURLConnection connection = null;
		OutputStream os = null;
		InputStream is = null;
		BufferedReader br = null;
		try {
			//创建连接对象
			URL url = new URL(httpUrl);
			//创建连接
			connection = (HttpURLConnection) url.openConnection();
			//设置请求方法
			connection.setRequestMethod("POST");
			//设置连接超时时间
			connection.setConnectTimeout(15000);
			//设置读取超时时间
			connection.setReadTimeout(15000);
			//DoOutput设置是否向httpUrlConnection输出，DoInput设置是否从httpUrlConnection读入，此外发送post请求必须设置这两个
			//设置是否可读取
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("appid",appid);
			//设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

			//拼装参数
			if (null != param && !param.equals("")) {
				//设置参数
				os = connection.getOutputStream();
				//拼装参数
				os.write(("="+param).getBytes("UTF-8"));
				//os.write("=qvJYRVdriY9zvby6gsD3gUKPEeDAaiIy9MhMOZ4i3C0E3UXX8d64badFr1JNskQLalMqlH7SntAdJoXg/JibzHL7J6ttM+FHz9TZ2nbksCVBWuhGgV1LiKf3BGyNbu2QUst+QM3+zntTFdhehckdSe5yQGOcr/4ROFtV6B6Z9AfuC0MZ3fL44/lvLvikXBhvocO4Y/lvw6pbHDfXYrfJuA==".getBytes());
			}
			//设置权限
			//设置请求头等
			//开启连接
			//connection.connect();
			//读取响应
			if (connection.getResponseCode() == 200) {
				is = connection.getInputStream();
				if (null != is) {
					br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
					String temp = null;
					while (null != (temp = br.readLine())) {
						result.append(temp);
						result.append("\r\n");
					}
				}
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//关闭连接
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			//关闭连接
			connection.disconnect();
		}
		return result.toString();
	}

	/**
	 * 提单错误直接失败
	 */
	private static Set<String> codesError = new HashSet<String>(){{
		add("0");
	}};


	/**
	 *
	 * @return
	 */
	public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
		if(upOrder != null ){
			UpOrder product = upOrderService.findOrderProduct(upOrder.getUporderuuid());
			if (product != null) {
				Map<String,String> headers = new HashMap<>();
				headers.put("appid",shopInfo.getAppId());
				JSONObject data = new JSONObject();
				data.put("OrderSN",upOrder.getUporderuuid());
				data.put("TimeStamp",new DateUtils().toTimeStamp());
				data.put("Sign",MD5.md5(StringSort.doSign(data).concat("&key=")+shopInfo.getUpkey()));

				try {
					//des = DESUtils.encrypt(data.toString(),shopInfo.getUpshopip().substring(4,12));
					String des = Base64Utils.encode(desEncrypt(data.toString().getBytes(),shopInfo.getUpshopip().substring(4,12),"UTF-8")) ;
					String res = HttpClient.post10086Url(shopInfo.getOrderStatusAddress(),"="+ des,headers);
					logger.info("queryzhaoguo:"+res+"data:"+data+",phone:"+upOrder.getUpphonenum());
					if(res != null){
						JSONObject result = JSONObject.parseObject(res);
						if(result.containsKey("code") && result.getString("code").equals("0")){
							UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
							if( result.getJSONObject("data").getString("State").equals("200") && order != null && order.getStatus() == Config.status[0] ){
								order.setRemark(result.containsKey("msg") ? result.getString("msg") : result.getString("State"));
								RechargeRest.successUpOrder.add(order);
							}else if((
									result.getJSONObject("data").getString("State").equals("400") ||
											result.getJSONObject("data").getString("State").equals("300")
							) && order != null && order.getStatus() == Config.status[0]){
								order.setRemark(result.containsKey("msg") ?	result.getString("msg") : Config.orderFailA);
								RechargeRest.failtUpOrder.add(order);
							}
						} else if(result.getString("code").equals("-1")){
							UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
							order.setRemark(result.containsKey("msg") ?	result.getString("msg") : Config.orderFailA);
							RechargeRest.failtUpOrder.add(order);
						}else{
							logger.debug("queryzhaoguo查询失败:"+upOrder.getUpphonenum());
						}
					}else{
						logger.info("queryzhaoguo order failt:"+upOrder.getUpphonenum());
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}else{
			logger.info("queryzhaoguo order failt:"+upOrder.getUpphonenum());
		}
	}
}

